//
//  TSPlaceholderTextView.swift
//  Pods
//
//  Created by 100Years on 2025/3/4.
//

open class TSPlaceholderTextView: UITextView {

    public lazy var placeholderLabel: UILabel = {
        let placeholderLabel = UILabel()
        placeholderLabel.font = font
        placeholderLabel.textColor = placeholderColor
        placeholderLabel.text = placeholder
        placeholderLabel.numberOfLines = 0
        placeholderLabel.isUserInteractionEnabled = false
        placeholderLabel.textAlignment = .left
        
        if kIsRTL {
            placeholderLabel.textAlignment = .right
        }

        return placeholderLabel
    }()
    
    public var maxLength:Int = 1000 {
        didSet {
            handleTextViewTextCount(textView: self)
        }
    }
    // Placeholder Text
    public  var placeholder: String? {
        didSet {
            placeholderLabel.text = placeholder
        }
    }
    
    // Placeholder Color
    public var placeholderColor: UIColor = .lightGray {
        didSet {
            placeholderLabel.textColor = placeholderColor
        }
    }
    
    // Placeholder Insets
    public var textInsets: UIEdgeInsets = .zero {
        didSet {
            updateTextContainerInset()
        }
    }
    
    // Override text property to manage placeholder visibility
    open override var text: String! {
        didSet {
            updatePlaceholderVisibility()
        }
    }
    
    public var textViewTextChanged:((String)->Void)?
    
    // Initializer
    public init(placeholder: String? = nil,
         text: String? = nil,
         font: UIFont? = nil,
         textColor: UIColor = .black,
         backgroundColor: UIColor = .white,
         textInsets: UIEdgeInsets = .zero) {
        super.init(frame: .zero, textContainer: nil)
        
        self.placeholder = placeholder
        self.font = font
        self.textColor = textColor
        self.backgroundColor = backgroundColor
        self.textInsets = textInsets
        
        setupPlaceholder()
        self.text = text
        
        if kIsRTL {
            // 1. 设置语义内容属性（强制RTL布局）
            semanticContentAttribute = .forceRightToLeft

            // 2. 创建段落样式设置文本方向
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.baseWritingDirection = .rightToLeft
            paragraphStyle.alignment = .right  // 或 .natural 让系统自动决定
            
            // 3. 应用到文本视图
            let attributes: [NSAttributedString.Key: Any] = [
                .paragraphStyle: paragraphStyle,
                .writingDirection: [NSWritingDirection.rightToLeft.rawValue],
                .foregroundColor:textColor
            ]
            typingAttributes = attributes
        }
        
    }
    
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
        setupPlaceholder()
    }
    
    // Setup placeholder label
    private func setupPlaceholder() {
 
        addSubview(placeholderLabel)
        updatePlaceholderVisibility()
        
        // 监听键盘/光标显示通知
           NotificationCenter.default.addObserver(
               self,
               selector: #selector(textViewDidBeginEditing(_:)),
               name: UITextView.textDidBeginEditingNotification,
               object: self
           )
    
        
        // Observe text changes to update placeholder
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(textDidChange(_:)),
                                               name: UITextView.textDidChangeNotification,
                                               object: self)
        
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(textDidChange(_:)),
                                               name: UITextView.textDidEndEditingNotification,
                                               object: self)
        
        NotificationCenter.default.addObserver(forName: UITextView.textDidEndEditingNotification, object: nil, queue: .main) { [weak self]  _ in
            guard let self = self else { return }
            updatePlaceholderVisibility()
        }
        
        // Update text container insets
        updateTextContainerInset()
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    // Update placeholder visibility
    private func updatePlaceholderVisibility() {
//        if text.isEmpty , self.isFirstResponder == false
//        {
//            placeholderLabel.isHidden = false
//        }
//        placeholderLabel.isHidden = true
        
        placeholderLabel.isHidden = !text.isEmpty
    }
    
    @objc private func textViewDidBeginEditing(_ notification: Notification) {
        placeholderLabel.isHidden = true
    }
    
    @objc private func textDidChange(_ notification: Notification) {
        if let textView = notification.object as? UITextView {
            handleTextViewTextCount(textView: textView)
            textViewTextChanged?(textView.text)
        }
        updatePlaceholderVisibility()
    }
    
    open func handleTextViewTextCount(textView:UITextView) {
        if textView.text.count > maxLength {
            textView.text = String(textView.text.prefix(maxLength))
        }
    }
    
    // Update textContainerInset and placeholder frame
    private func updateTextContainerInset() {
        textContainerInset = textInsets
        setNeedsLayout()
    }

    
    // Layout placeholder
    open override func layoutSubviews() {
        super.layoutSubviews()
        let placeholderX = textInsets.left+5
        let placeholderY = textInsets.top
        let placeholderWidth = bounds.width - placeholderX - textInsets.right
//        let placeholderHeight = bounds.height - textInsets.top - textInsets.bottom
        let placeholderHeight = placeholderLabel.sizeThatFits(CGSize(width: placeholderWidth, height: .greatestFiniteMagnitude)).height
        placeholderLabel.frame = CGRect(x: placeholderX, y: placeholderY, width: placeholderWidth, height: placeholderHeight)
    }

}


